package controllers

import (
	"github.com/beego/beego/v2/server/web"
)

type BaseController struct {
	web.Controller
}

func (c *BaseController) Prepare() {
	origin := c.Ctx.Input.Header("Origin")
	if origin == "" {
		origin = "http://localhost:5173"
	}

	// 允许跨域
	c.Ctx.Output.Header("Access-Control-Allow-Origin", origin)
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "Origin, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, X-Requested-With")
	c.Ctx.Output.Header("Access-Control-Allow-Credentials", "true")
	c.Ctx.Output.Header("Access-Control-Max-Age", "86400")
	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")

	// 处理 OPTIONS 请求
	if c.Ctx.Request.Method == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
}
